package org.example.httpserver.controller;

import org.example.httpserver.entity.Person;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;


@RestController
public class PictureController {
    private final Logger logger = LoggerFactory.getLogger("pictureController");

    @RequestMapping("/start/springboot")
    public String startSpringBoot() {
        logger.info("hello");
        return "hello";
    }

    /*
     * app端采用的是 post传递的FormBody*/
    @RequestMapping("/form/post")
    public String getLoginInfo(@RequestParam("username") String username, @RequestParam("password") String password) {
        /*
        * @RequestParam Map<String, String> map 这样接收也是可以的，但是如果参数较多还是建议使用Map接收
        * 不能用实体类接收 会报错*/
        logger.info(username);
        logger.info(password);
        return username;
    }

    @RequestMapping("/form/body")
    public String postBody(@RequestBody Person person) {
        logger.info(person.toString());
        return person.toString();

        /*
        * 此处用实体类Person接收可以,但是注解一定要@RequestBody
        * 用Map<String,String> map接收也可行,但是此时必须要用@RequestBody注解
        */
    }

    @RequestMapping("/MultipartPost")
    public String getMultipartPost(@RequestParam("username") String username, @RequestParam("password") String password,
                                   @RequestParam("image") MultipartFile file
    ) throws IOException {

        /*@RequestParam Map<String, String> map也是可行，但是接收文件时，会显示map.get("image")为null，
        所以不建议用这种方式

        * @RequestParam("username") String username, @RequestParam("password") String password,
                                   @RequestParam("image") MultipartFile file*/

        /*
        * @RequestBody不可行*/
        logger.info(username);
        logger.info(password);
        logger.info(file.toString());
        String fileName = file.getOriginalFilename();
        String filePath = "D:\\" +fileName;
        logger.info(filePath);
        file.transferTo(new File(filePath));
        return username +" "+password+" "+file.getOriginalFilename();
    }

}
